import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { Picker, ScrollView, View } from "@tarojs/components";
import { useMap, useCreation, useSetState, useUpdateEffect } from "ahooks";

import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import Page from "@/components/common/Page";
import ByTabs from "@/components/ui/ByTabs";
import ByText from "@/components/ui/ByText";
import ByIcon from "@/components/ui/ByIcon";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import ByCheckbox from "@/components/ui/ByCheckbox";
import FormInput from "@/components/common/FormInput";
import BySearchBar from "@/components/ui/BySearchBar";
import TreeMenu from "@/packageProject/components/TreeMenu";

import useList from "@/hooks/useList";
import ApiBudget from "@/api/budget";

import { MasterBudgetItem, MaterialBudgetItem } from "@/types/budget";

const tabList = [
  { label: "主材", value: 1 },
  { label: "辅材", value: 2 },
  { label: "家具", value: 3 },
  { label: "电器", value: 4 },
  { label: "灯具窗帘", value: 5 },
  { label: "测量", value: 6 },
];

const pickerRange = [
  { label: "材料", value: "MaterialClass" },
  { label: "区域", value: "Area" },
  { label: "品类", value: "Category" },
];

const Item = ({
  checked,
  source,
  onClick,
}: {
  checked: boolean;
  source: MaterialBudgetItem;
  onClick: () => void;
}) => {
  return (
    <View
      className={`my-2 p-3 rounded-xl border-1 ${
        checked
          ? "bg-[var(--color-primary-bg)] border-primary"
          : "bg-white border-white"
      }`}
      onClick={onClick}
    >
      <ByRow align="center" wrap={false}>
        <ByCol span={"auto"} className="ml-1">
          <ByRow content="between">
            <ByText bold size="sm">
              {source.materialName}
            </ByText>

            <ByText size="xs" type="third">
              {/* 无限制 */}
              最大申请量:{source.maxApplyNum}
            </ByText>
          </ByRow>

          <ByRow content="between" className="mt-2">
            <View className="text-center">
              <ByText bold>{source.applyNum || 0}</ByText>
              <View>
                <ByText type="third" size="xs">
                  已申请
                </ByText>
              </View>
            </View>

            <View className="text-center">
              <ByText bold>{source.billNum}</ByText>
              <View>
                <ByText type="third" size="xs">
                  已开单
                </ByText>
              </View>
            </View>

            <View className="text-center">
              <ByText bold>{source.jsNum}</ByText>
              <View>
                <ByText type="third" size="xs">
                  结算量
                </ByText>
              </View>
            </View>
          </ByRow>
        </ByCol>
      </ByRow>
    </View>
  );
};

const TreeItem = ({
  source,
  selectedNum = 0,
  onSetAll,
}: {
  source: MasterBudgetItem;
  selectedNum?: number;

  onSetAll: () => void;
}) => {
  const { materialData } = source;
  const total = materialData.length;

  return (
    <View className="flex items-center">
      <ByCheckbox
        checked={selectedNum === total}
        indeterminate={selectedNum > 0}
        onChange={onSetAll}
      />

      <View className="ml-1.5 flex-auto">
        {source.className}
        {selectedNum > 0 && <ByText type="third">({selectedNum || 0})</ByText>}
      </View>
    </View>
  );
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const [keyword, setKeyword] = useState<string>();

  const [search, setSearch] = useSetState({
    intentCustomerId,
    materielCategory: 1,
    groupBy: "MaterialClass",
  });

  // 材料列表
  const { resetToFirst, list, loading } = useList<MasterBudgetItem>(
    ApiBudget.getMasterBudget,
    { defaultParams: [search] }
  );

  // 选中项
  const [selectedMap, { set, get, reset, setAll }] = useMap<number, Set<any>>();

  // 激活索引
  const [activeIndex, setActiveIndex] = useState<number>(0);

  const pickerChange = (e) => {
    const index = e.detail.value;
    const target = pickerRange[index];
    setSearch({ groupBy: target.value });
  };

  useUpdateEffect(() => {
    reset();
    setActiveIndex(0);
    resetToFirst(search);
  }, [search]);

  const pickerIndex = pickerRange.findIndex(
    ({ value }) => value === search.groupBy
  );

  const handleSelected = (item: MaterialBudgetItem) => {
    let selected = get(activeIndex) || new Set();

    if (selected.has(item)) {
      selected.delete(item);
    } else {
      selected.add(item);
    }

    set(activeIndex, selected);
  };

  const handleConfirm = async () => {
    Taro.navigateTo({
      url: `cart?intentCustomerId=${intentCustomerId}`,

      events: {
        updateCartOriginData(data) {
          // 强制更新
          //  data === selectedMap
          setAll(selectedMap);
        },
      },

      success(res) {
        const details = [...selectedMap.values()].reduce((ary, item) => {
          return [...ary, ...item.values()];
        }, [] as any[]);

        const { materielCategory } = search;
        const target = tabList.find((e) => e.value === materielCategory);

        res.eventChannel.emit("accpetBudgetDetails", {
          map: selectedMap,
          // details,
          materielCategory,
          materielCategoryText: target!.label,
        });
      },
    });
  };

  // 全选/取消全选
  const handleSetAll = (index: number) => {
    const stock = get(index) || new Set();
    const { materialData } = list[index];

    if (stock.size === materialData.length) {
      // 清空
      stock.clear();
    } else {
      // 全部加进去
      materialData.forEach((e) => stock.add(e));
    }

    set(index, stock);
    setActiveIndex(index);
  };

  const { materialData = [] } = list[activeIndex] || {};

  // 本地搜索筛选
  const renderMaterialData = useCreation(() => {
    if (!keyword || materialData.length === 0) return materialData;

    return materialData.filter((e) => e.masterName.includes(keyword));
  }, [keyword, materialData]);

  return (
    <>
      <Page
        skyline
        slotFooter={
          <ByButton
            size="large"
            className="w-2/3"
            disabled={selectedMap.size === 0}
            onClick={handleConfirm}
          >
            申报
          </ByButton>
        }
        slotHeader={
          <View className="bg-white">
            <View className="px-2 pb-2">
              <ByRow align="center">
                <ByCol span={"auto"}>
                  <ByTabs
                    capsule
                    tabs={tabList}
                    active={search.materielCategory}
                    onChange={(e) => setSearch({ materielCategory: e })}
                  />
                </ByCol>
                <ByCol span={"none"} className="ml-1">
                  <ByButton
                    round
                    size="small"
                    variant="outline"
                    to={`optional?intentCustomerId=${intentCustomerId}`}
                  >
                    自选
                  </ByButton>
                </ByCol>
              </ByRow>

              <ByRow className="mt-2">
                <Picker
                  className="w-[200px] mr-2"
                  value={pickerIndex}
                  range={pickerRange}
                  rangeKey="label"
                  onChange={pickerChange}
                >
                  <FormInput
                    round
                    size="sm"
                    disabled
                    value={pickerRange[pickerIndex]["label"]}
                    suffix={
                      <ByIcon name="ArrowBottom" className="text-third" />
                    }
                  />
                </Picker>

                <ByCol span={"auto"}>
                  <BySearchBar
                    circle
                    placeholder="搜索"
                    onClear={setKeyword}
                    onConfirm={setKeyword}
                  />
                </ByCol>
              </ByRow>
            </View>
          </View>
        }
      >
        <View className="flex h-full">
          <View
            className={`flex-none bg-[#f1f3f8] h-full bg-error overflow-auto duration-200${
              list.length == 0 ? "w-[0]" : "w-[210px]"
            }`}
          >
            <TreeMenu
              list={list}
              active={activeIndex}
              showCheckbox
              onClick={setActiveIndex}
              renderItem={(item, index) => (
                <TreeItem
                  source={item}
                  selectedNum={selectedMap.get(index)?.size}
                  onSetAll={() => handleSetAll(index)}
                />
              )}
            />
          </View>
          <View className="flex-auto h-full">
            <ScrollView scrollY className="h-full">
              <ListView
                key={activeIndex}
                className="p-2"
                loading={loading}
                isEmpty={renderMaterialData.length === 0}
              >
                {renderMaterialData.map((item, index) => (
                  <Item
                    source={item}
                    key={activeIndex + "_" + index + "_" + item.materialId}
                    checked={!!get(activeIndex)?.has(item)}
                    onClick={() => handleSelected(item)}
                  />
                ))}
              </ListView>
            </ScrollView>
          </View>
        </View>
      </Page>
    </>
  );
};
